package com.gitee.linmt.service.impl;

import com.gitee.linmt.entity.SysRole;
import com.gitee.linmt.exception.ServiceException;
import com.gitee.linmt.repository.SysRoleRepository;
import com.gitee.linmt.service.SysRoleService;
import org.springframework.stereotype.Service;

/**
 * 角色 Service 实现类.
 *
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    
    private final SysRoleRepository roleRepository;
    
    public SysRoleServiceImpl(SysRoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }
    
    @Override
    public SysRole save(SysRole sysRole) {
        checkRoleInfo(sysRole);
        return roleRepository.save(sysRole);
    }
    
    @Override
    public SysRole update(SysRole sysRole) {
        checkRoleInfo(sysRole);
        return roleRepository.saveAndFlush(sysRole);
    }
    
    @Override
    public boolean delete(Long deleteId) {
        roleRepository.deleteById(deleteId);
        return true;
    }
    
    private void checkRoleInfo(SysRole role) {
        role.setRoleName(role.getRoleName().toUpperCase());
        SysRole sysRole = roleRepository.getByRoleName(role.getRoleName());
        if (sysRole != null && !sysRole.getId().equals(role.getId())) {
            throw new ServiceException("S0101", role.getRoleName());
        }
        if (role.getParentId() != null) {
            if (!roleRepository.existsById(role.getParentId())) {
                throw new ServiceException("S0102", role.getParentId());
            }
        }
    }
}
